/**
 * Copyright (c) 2020 铭软科技(mingsoft.net)
 * 本软件及相关文档文件（以下简称“软件”）的版权归 铭软科技 所有
 * 遵循铭软科技《保密协议》
 */
package net.mingsoft.mwebsite.action;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.biz.IManagerBiz;
import net.mingsoft.basic.biz.IModelBiz;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.constant.e.ManagerAdminEnum;
import net.mingsoft.basic.entity.ManagerEntity;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.StringUtil;
import net.mingsoft.mwebsite.biz.IWebsiteBiz;
import net.mingsoft.mwebsite.entity.WebsiteEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 站群
 * 
 * @author 铭软团队
 * @version 版本号：100-000-000<br/>
 *          创建日期：2016年1月12日<br/>
 *          历史修订：<br/>
 */
@Controller
@RequestMapping("/${ms.manager.path}/website/manager")
public class WebsiteManagerAction extends BaseAction {

	/**
	 * appBiz业务层的注入
	 */
	@Autowired
	private IWebsiteBiz websiteBiz;

	/**
	 * managerBiz业务层的注入
	 */
	@Autowired
	private IManagerBiz managerBiz;

	@Autowired
	private IModelBiz modelBiz;

	/**
	 * 返回设置管理员form页面
	 */
	@ApiOperation(value = "返回设置管理员form页面")
	@GetMapping("/form")
	public String index(HttpServletResponse response,HttpServletRequest request,@ApiIgnore ModelMap mode){
		return "/mwebsite/form";
	}

	/**
	 * 编辑站点管理员
	 * 
	 * @param request
	 * @param response
	 */
	@ApiOperation(value = "编辑站点管理员")
	@PostMapping("{websiteId}/edit")
	@ResponseBody
	public ResultData edit(@PathVariable int websiteId, HttpServletRequest request, HttpServletResponse response) {
		// 读取站点信息
		WebsiteEntity website = websiteBiz.getOne(Wrappers.<WebsiteEntity>lambdaQuery().eq(WebsiteEntity::getWebsiteId, websiteId));
		if (website != null) {
            ManagerEntity managerEntity = websiteBiz.getManageByAppId(website.getWebsiteId());
            if (managerEntity != null) {
				// 读取管理员信息
				managerEntity.setManagerPassword("");
				return ResultData.build().success(managerEntity);
			} else {
				return ResultData.build().error();
			}
		}
		return ResultData.build().error();
	}

	/**
	 * 更新站点管理员
	 * 
	 * @param request
	 * @param response
	 */
	@ApiOperation(value = "更新站点管理员")
	@LogAnn(title = "更新站点管理员",businessType= BusinessTypeEnum.UPDATE)
	@PostMapping("/update")
	@ResponseBody
	public ResultData update(@ModelAttribute @ApiIgnore  ManagerEntity manager, HttpServletRequest request,
			HttpServletResponse response) {
		managerBiz.updateCache();
		int websiteId = BasicUtil.getInt("managerWebsiteId");
		String modelIds = request.getParameter("modelIds");
		WebsiteEntity website = websiteBiz.getOne(Wrappers.<WebsiteEntity>lambdaQuery().eq(WebsiteEntity::getWebsiteId, websiteId));

		if (website != null) {
			// 更新
			ManagerEntity managerEntity = websiteBiz.getManageByAppId(website.getWebsiteId());
			if (managerEntity != null) {

				ManagerEntity _managerEntity = new ManagerEntity();
				_managerEntity.setManagerName(manager.getManagerName());
				_managerEntity = (ManagerEntity) managerBiz.getEntity(_managerEntity);
				//如果查询出的账号有重复并且并非自身则不允许更新
				if (_managerEntity != null && !_managerEntity.getId().equals(manager.getId())) {
					return ResultData.build().error(getResString("err.exist",this.getResString("managerName")));
				}

				// 只更新昵称、密码、权限
				if (manager.getManagerPassword().length()>0 && !StringUtils.isBlank(manager.getManagerPassword()) && !managerEntity.getManagerPassword()
						.equals(SecureUtil.md5(manager.getManagerPassword()))) {
					manager.setManagerPassword(SecureUtil.md5(manager.getManagerPassword()));
				} else {
					manager.setManagerPassword(null);
				} 
				manager.setId(managerEntity.getId());
				manager.setRoleId(managerEntity.getRoleId());
				if (!StringUtils.isBlank(modelIds) && modelIds.split(",").length > 0) {
					int[] ids =  StringUtil.stringsToInts(modelIds.split(","));
					websiteBiz.updateManager(manager, ids);
				} else {
					websiteBiz.updateManager(manager, null);
				}
				return ResultData.build().success();
			} else {
				// 新增
				ManagerEntity _managerEntity = new ManagerEntity();
				_managerEntity.setManagerName(manager.getManagerName());
				if (managerBiz.getEntity(_managerEntity) != null) {
					return ResultData.build().error(getResString("err.exist",this.getResString("managerName")));
				}
				manager.setManagerPassword(SecureUtil.md5(manager.getManagerPassword()));
				manager.setManagerAdmin(ManagerAdminEnum.SUPER.toString());
				if (!StringUtils.isBlank(modelIds)) {
					websiteBiz.save(website, manager, StringUtil.stringsToInts(modelIds.split(",")));
				} else {
					websiteBiz.save(website, manager, null);
				}
				return ResultData.build().success();
			}

		}
		return ResultData.build().error(getResString("err.not.exist",this.getResString("website")));
	}

}
